package model

import (
	"gorm.io/gorm"
	"time"
)

type CProduct struct {
	gorm.Model

	Name        string `json:"name" gorm:"type:varchar(255);comment:名称"`
	MainPic     string `json:"mainPic" gorm:"type:varchar(255);comment:产品主图"`
	Sold        uint16 `json:"sold" gorm:"type:int(4);comment:售出数量"`
	Description string `json:"description" gorm:"type:longtext;comment:产品描述"`
	CommonPrice uint16 `json:"commonPrice" gorm:"type:smallint(5) unsigned;comment:价格"`
	MemberPrice uint16 `json:"memberPrice" gorm:"type:smallint(5) unsigned;comment:价格"`
	VipPrice    uint16 `json:"vipPrice" gorm:"type:smallint(5) unsigned;comment:价格"`

	DownloadUrl   string     `gorm:"size:255;comment:下载地址"`
	Pwd           string     `gorm:"size:32;comment:下载密码"`
	DownloadType  uint8      `gorm:"comment:下载类型，1：百度"`
	PwdUpdatedDay *time.Time `gorm:"comment:拉取Download时间"`
	UpdatedDay    *time.Time `gorm:"comment:外部平台更新时间"`
}

func (t *CProduct) TableName() string {
	return "c_product"
}

func (r *CProduct) GetAll() []uint {
	var codes []uint
	//GetDB().Model(&CProduct{}).Where("description is null or description = ''").Pluck("code", &codes)
	GetDB().Model(&CProduct{}).Where("1=1").Pluck("id", &codes)
	return codes
}

func (r *CProduct) Create(product *CProduct) error {
	return GetDB().Create(product).Error
}

func (r *CProduct) Update(product *CProduct) error {
	return GetDB().Save(product).Error
}

func (r *CProduct) FirstById(id uint64) (*CProduct, error) {
	var product CProduct
	err := GetDB().Where("id = ?", id).First(&product).Error
	return &product, err
}

func (r *CProduct) GetNoDownloadUrl(limit int) (arr []*CProduct, err error) {
	err = GetDB().Model(&CProduct{}).Where("download_url = ''").Order("id desc").Limit(limit).Scan(&arr).Error
	return
}

func (r *CProduct) GetDownloads(limit int) (arr []*CProduct, err error) {
	db := GetDB().Model(&CProduct{}).Where("download_type != 0")
	if limit > 0 {
		db.Limit(limit)
	}
	err = db.Scan(&arr).Error
	return
}
